package com.avengers.common.kit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

import static com.avengers.core.bean.Numbers.*;


/**
 * @author chenhai
 * @date 2018-11-08
 */
public class ImageFormatTransfer {
    private static final Logger logger = LoggerFactory.getLogger(ImageFormatTransfer.class);

    static boolean transfer(String srcPath, String destPath, String format, Integer maxPx) {
        boolean flag = false;
        try {
            File file = new File(srcPath);
            File destFile = new File(destPath);
            if (!destFile.getParentFile().exists()) {
                if (!destFile.getParentFile().mkdir()) {
                    logger.error("create dir  fail {}", destFile.getAbsolutePath());
                }
            }
            // 读入文件
            BufferedImage src = ImageIO.read(file);
            BigDecimal sourceWidth = BigDecimal.valueOf(src.getWidth());
            BigDecimal sourceHeight = BigDecimal.valueOf(src.getHeight());
            BigDecimal targetWidth = sourceWidth;
            BigDecimal targetHeight = sourceHeight;
            if (null != maxPx) {
                BigDecimal bDMaxPx = BigDecimal.valueOf(maxPx);
                if (sourceWidth.compareTo(sourceHeight) > 0) {
                    if (sourceWidth.compareTo(bDMaxPx) > 0) {
                        targetWidth = bDMaxPx;
                        targetHeight = sourceHeight.divide(sourceWidth, INT_2, RoundingMode.UP).multiply(targetWidth).setScale(INT_0, RoundingMode.UP);
                    }
                } else {
                    if (targetHeight.compareTo(bDMaxPx) > 0) {
                        targetHeight = bDMaxPx;
                        targetWidth = sourceWidth.divide(sourceHeight, INT_2, RoundingMode.UP).multiply(targetHeight).setScale(INT_0, RoundingMode.UP);
                    }
                }
                logger.info("transfer new file size: {} * {} ", targetWidth, targetHeight);
            }
            Image image = src.getScaledInstance(targetWidth.intValue(), targetHeight.intValue(), INT_1);
            BufferedImage bufferedImage = new BufferedImage(targetWidth.intValue(), targetHeight.intValue(), BufferedImage.TYPE_INT_RGB);
            Graphics graphics = bufferedImage.getGraphics();
            graphics.drawImage(image, 0, 0, Color.WHITE, null);
            graphics.dispose();
            // 输出到文件流
            flag = ImageIO.write(bufferedImage, format, new FileOutputStream(destFile));
        } catch (IOException e) {
            logger.error("transfer from {} to {} img error: {}", srcPath, destPath, e.getMessage(), e);
        }
        return flag;
    }
}
